import os
import re
from recipe import RecipeXml
from ftp import FtpSender
from PyFlac.Carbon import CarbonUtils
from PyFlac.Carbon import CarbonJob
from PyFlac.Carbon import CarbonSocketLayer
import time

# Path donde se dejan las promos una vez finalizadas
TEMPORAL_PATH     = "/data/temp/"
TEMPORAL_UNC_PATH = "\\\\10.221.173.151\\recipe_temp"
CARBON_HOST       = "10.221.173.31"


def GetBasename(filename = ''):
	print filename
	(base, ext) = filename.split(".")
	return base



def RecipeCarbonTask(recipe = None, carbon_host = None, src_unc = None, dst_unc  = None, src_file = None):

	if (recipe != None and carbon_host != None and src_unc != None and dst_unc != None and src_file != None):
		
		basename = GetBasename(src_file)

		dst = {'d_guid': recipe.guid, 'd_basename' : basename, 'd_path': dst_unc }
		carbon = CarbonSocketLayer.CarbonSocketLayer(carbon_host)
		Xml    = CarbonUtils.CreateCarbonXMLJob(src_unc, src_file, [], [dst])
		job    = CarbonJob.CarbonJob(carbon,Xml)
		if job.Start():
			status = job.GetStatus(True)
			while status == "STARTED" or status == "QUEUED":
				time.sleep(10)
				status = job.GetStatus(True)

			if status == "COMPLETED":
				return (True, basename + recipe.ext, status)
			else:
				return (False, '' ,status)
		else:
			return (False, '', "ERROR")




def RecipeSendTask(recipe = None, src_path = None, src_file = None):
	
	if recipe != None and src_path != None and src_file != None:

		ftp = FtpSender()
			
		(ret, err) = ftp.Connect(recipe.host, recipe.user, recipe.passwd)
		if ret == False:
			return (ret, err)

		(ret, err) = ftp.Cwd(recipe.path)
		if ret == False:
			ftp.Disconnect()
			return (ret, err)

		(ret, err) = ftp.Send(src_path + src_file, src_file)
		ftp.Disconnect()
		return (ret, err)
						


def RecipeTask (recipe = '', src_file_name = '', src_unc_path = ''):

	job = RecipeXml(recipe)
	if job != None:

		for target in job.target:
			print "Realizando tarea: " + target.name
			print "Transcode: " + str(target.transcode)
			print "Transcode Method: " + target.transcodemethod

			
			if target.transcode == True and target.transcodemethod == 'carbon':
				(ret, filename, msg) = RecipeCarbonTask(target.transcoder, CARBON_HOST, src_unc_path, TEMPORAL_UNC_PATH, src_file_name)	
				print "Transcoder Return: " + str(ret)
				print "Filename: " + filename
				if ret == True:
					if os.path.isfile(TEMPORAL_PATH + filename):
						for dst in target.destination:
							(ret, msg) = RecipeSendTask(dst, TEMPORAL_PATH, filename)		
							print "Retorno: " + str(ret)
					





